
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Model," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>新建、更新、删除记录 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        新建、更新、删除记录
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Model/" rel="tag">Ember-Model</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 8 分钟</span>
    </header>

    <div class="post-content">
      <p>前一篇介绍了查询方法，本篇介绍新建、更新、删除记录的方法。<br>本篇的示例代码创建在上一篇的基础上。对于整合<a target="_blank" rel="noopener" href="http://www.firebase.com/">firebase</a>、创建<code>route</code>和<code>template</code>请参看上一篇，增加一个controller：<code>ember g controller articles</code>。</p>
<h2 id="1，新建记录"><a href="#1，新建记录" class="headerlink" title="1，新建记录"></a>1，新建记录</h2><p>创建新的记录使用<code>createRecord()</code>方法。比如下面的代码新建了一个<code>aritcle</code>记录。修改模板，在模板上增加几个<code>input</code>输入框用于输入<code>article</code>信息。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  app/templates/articles.hbs  --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;container&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;row&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4 col-xs-4&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;list-group&quot;</span>&gt;</span></span><br><span class="line">            &#123;&#123;#each model as |item|&#125;&#125;</span><br><span class="line">                <span class="tag">&lt;<span class="name">li</span> <span class="attr">class</span>=<span class="string">&quot;list-group-item&quot;</span>&gt;</span></span><br><span class="line">                    <span class="comment">&lt;!--设置路由，路由的层级与router.js里定义的要一致 --&gt;</span></span><br><span class="line">                     &#123;&#123;#link-to &#x27;articles.article&#x27; item.id&#125;&#125;</span><br><span class="line">                        &#123;&#123;item.title&#125;&#125; -- <span class="tag">&lt;<span class="name">small</span>&gt;</span>&#123;&#123;item.category&#125;&#125;<span class="tag">&lt;/<span class="name">small</span>&gt;</span></span><br><span class="line">                    &#123;&#123;/link-to&#125;&#125;</span><br><span class="line">                <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            &#123;&#123;/each&#125;&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            <span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">                title：&#123;&#123;input value=title&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">                body： &#123;&#123;textarea value=body cols=&quot;80&quot; rows=&quot;3&quot;&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">                category: &#123;&#123;input value=category&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">button</span> &#123;&#123; <span class="attr">action</span> &quot;<span class="attr">saveItem</span>&quot;&#125;&#125;&gt;</span>保存<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">font</span> <span class="attr">color</span>=<span class="string">&#x27;red&#x27;</span>&gt;</span>&#123;&#123;tipInfo&#125;&#125;<span class="tag">&lt;/<span class="name">font</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-8 col-xs-8&quot;</span>&gt;</span></span><br><span class="line">        &#123;&#123;outlet&#125;&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>页面的字段分别对应这模型<code>article</code>的属性。点击“保存”后提交到<code>controller</code>处理。下面是获取数据保存数据的<code>controller</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   app/controllers/articles.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line"></span><br><span class="line">    actions: &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//  表单提交，保存数据到Store。Store会自动更新到firebase</span></span><br><span class="line">        saveItem: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> title = <span class="built_in">this</span>.get(<span class="string">&#x27;title&#x27;</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="string">&#x27;undefined&#x27;</span> === <span class="keyword">typeof</span>(title) || <span class="string">&#x27;&#x27;</span> === title.trim()) &#123;</span><br><span class="line">                <span class="built_in">this</span>.set(<span class="string">&#x27;tipInfo&#x27;</span>, <span class="string">&quot;title不能为空&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> ;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">var</span> body = <span class="built_in">this</span>.get(<span class="string">&#x27;body&#x27;</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="string">&#x27;undefined&#x27;</span> === <span class="keyword">typeof</span>(body) || <span class="string">&#x27;&#x27;</span> === body.trim()) &#123;</span><br><span class="line">                <span class="built_in">this</span>.set(<span class="string">&#x27;tipInfo&#x27;</span>, <span class="string">&quot;body不能为空&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> ;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">var</span> category = <span class="built_in">this</span>.get(<span class="string">&#x27;category&#x27;</span>);</span><br><span class="line">            <span class="keyword">if</span> (<span class="string">&#x27;undefined&#x27;</span> === <span class="keyword">typeof</span>(category) || <span class="string">&#x27;&#x27;</span> === category.trim()) &#123;</span><br><span class="line">                <span class="built_in">this</span>.set(<span class="string">&#x27;tipInfo&#x27;</span>, <span class="string">&quot;category不能为空&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span> ;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//  创建数据记录</span></span><br><span class="line">            <span class="keyword">var</span> article = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;article&#x27;</span>, &#123;</span><br><span class="line">                title: title,</span><br><span class="line">                body: body,</span><br><span class="line">                category: category,</span><br><span class="line">                timestamp: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime()</span><br><span class="line">            &#125;);</span><br><span class="line">            article.save();  <span class="comment">//保存数据的到Store</span></span><br><span class="line">            <span class="comment">//  清空页面的input输入框</span></span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;title&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;body&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;category&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>主要看<code>createRecord</code>方法，第一个参数是模型名称。第二个参数是个哈希，在哈希总设置模型属性值。最后调用<code>article.save()</code>方法把数据保存到<code>Store</code>，再由<code>Store</code>保存到firebase。运行效果如下图：</p>
<p><img src="http://static.oschina.net/uploads/img/201510/21020549_6yDj.png" alt="结果截图"></p>
<p>输入信息，点击“保存”后数据立刻会显示在列表”no form – java”之后。然后你可以点击标题查询详细信息，body的信息会在页面后侧显示。</p>
<p>通过这里实例我想你应该懂得去使用<code>createRecord()</code>方法了！但是如果有两个模型是有关联关系保存的方法又是怎么样的呢？下面再新增一个模型。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ember g model users</span><br></pre></td></tr></table></figure>
<p>然后在模型中增加关联。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   app/models/article.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> DS <span class="keyword">from</span> <span class="string">&#x27;ember-data&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> DS.Model.extend(&#123;</span><br><span class="line">    title: DS.attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">    body: DS.attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">    timestamp: DS.attr(<span class="string">&#x27;number&#x27;</span>),</span><br><span class="line">    category: DS.attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">    author: DS.belongsTo(<span class="string">&#x27;user&#x27;</span>)  <span class="comment">//关联user</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//  app/models/user.js</span></span><br><span class="line"><span class="keyword">import</span> DS <span class="keyword">from</span> <span class="string">&#x27;ember-data&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> DS.Model.extend(&#123;</span><br><span class="line">      username: DS.attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">      timestamp: DS.attr(<span class="string">&#x27;number&#x27;</span>),</span><br><span class="line">      articles: DS.hasMany(<span class="string">&#x27;article&#x27;</span>)  <span class="comment">//关联article</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>修改模板<code>articles.hbs</code>在界面上增加录入作者信息字段。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">⋯⋯省略其他代码</span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">    title：&#123;&#123;input value=title&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    body： &#123;&#123;textarea value=body cols=&quot;80&quot; rows=&quot;3&quot;&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    category: &#123;&#123;input value=category&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    author: &#123;&#123;input value=username&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> &#123;&#123; <span class="attr">action</span> &quot;<span class="attr">saveItem</span>&quot;&#125;&#125;&gt;</span>保存<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">font</span> <span class="attr">color</span>=<span class="string">&#x27;red&#x27;</span>&gt;</span>&#123;&#123;tipInfo&#125;&#125;<span class="tag">&lt;/<span class="name">font</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">⋯⋯省略其他代码</span><br></pre></td></tr></table></figure>
<p>下面看看怎么在<code>controller</code>中设置这两个模型的关联关系。一共有两种方式设置，一种是直接在<code>createRecord()</code>方法中设置，另一种是在方法外设置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   app/controllers/articles.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line"></span><br><span class="line">    actions: &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//  表单提交，保存数据到Store。Store会自动更新到firebase</span></span><br><span class="line">        saveItem: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="comment">//  获取信息和校验代码省略⋯⋯</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 创建user</span></span><br><span class="line">            <span class="keyword">var</span> user = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;user&#x27;</span>, &#123;</span><br><span class="line">                username: username,</span><br><span class="line">                timestamp: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime()</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="comment">//  必须要执行这句代码，否则user数据不能保存到Store，</span></span><br><span class="line">            <span class="comment">//  否则article通过user的id查找不到user</span></span><br><span class="line">            user.save();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//  创建article</span></span><br><span class="line">            <span class="keyword">var</span> article = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;article&#x27;</span>, &#123;</span><br><span class="line">                title: title,</span><br><span class="line">                body: body,</span><br><span class="line">                category: category,</span><br><span class="line">                timestamp: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime(),</span><br><span class="line">                author: user   <span class="comment">//设置关联</span></span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            article.save();  <span class="comment">//保存数据的到Store</span></span><br><span class="line">            <span class="comment">//  清空页面的input输入框</span></span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;title&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;body&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;category&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;username&#x27;</span>, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201510/21020549_Trle.png" alt="界面截图"></p>
<p>输入上如所示信息，点击“保存”可以在firebase的后台看到如下的数据关联关系。</p>
<p><img src="http://static.oschina.net/uploads/img/201510/21020549_wrzD.png" alt="firebase数据截图"></p>
<p>注意点：与这两个数据的关联是通过数据的<code>id</code>维护的。<br>那么如果我要通过<code>article</code>获取<code>user</code>的信息要怎么获取呢？</p>
<p>直接以面向对象的方式获取既可。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;#each model as |item|&#125;&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">li</span> <span class="attr">class</span>=<span class="string">&quot;list-group-item&quot;</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!--设置路由，路由的层级与router.js里定义的要一致 --&gt;</span></span><br><span class="line">         &#123;&#123;#link-to &#x27;articles.article&#x27; item.id&#125;&#125;</span><br><span class="line">            &#123;&#123;item.title&#125;&#125; -- <span class="tag">&lt;<span class="name">small</span>&gt;</span>&#123;&#123;item.category&#125;&#125;<span class="tag">&lt;/<span class="name">small</span>&gt;</span> -- <span class="tag">&lt;<span class="name">small</span>&gt;</span>&#123;&#123;item.author.username&#125;&#125;<span class="tag">&lt;/<span class="name">small</span>&gt;</span></span><br><span class="line">        &#123;&#123;/link-to&#125;&#125;</span><br><span class="line">    <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">&#123;&#123;/each&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>注意看助手<code>&#123;&#123; item.author.username &#125;&#125;</code>。很像EL表达式吧！！<br>前面提到过有两个方式设置两个模型的关联关系。下面的代码是第二种方式：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  其他代码省略⋯⋯</span></span><br><span class="line"><span class="comment">//  创建article</span></span><br><span class="line"><span class="keyword">var</span> article = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;article&#x27;</span>, &#123;</span><br><span class="line">    title: title,</span><br><span class="line">    body: body,</span><br><span class="line">    category: category,</span><br><span class="line">    timestamp: <span class="keyword">new</span> <span class="built_in">Date</span>().getTime()</span><br><span class="line">    <span class="comment">// ,</span></span><br><span class="line">    <span class="comment">// author: user   //设置关联</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第二种设置关联关系方法，在外部手动调用set方法设置</span></span><br><span class="line">article.set(<span class="string">&#x27;author&#x27;</span>, user);</span><br><span class="line"><span class="comment">//  其他代码省略⋯⋯</span></span><br></pre></td></tr></table></figure>
<p>运行，重新录入信息，得到的结果是一致的。甚至你可以直接在<code>createRecord</code>方法里调用方法来设置两个模型的关系。比如下面的代码段：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> store = <span class="built_in">this</span>.store;  <span class="comment">// 由于作用域问题，在createRecord方法内部不能使用this.store</span></span><br><span class="line"><span class="keyword">var</span> article = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;article&#x27;</span>, &#123;</span><br><span class="line">    title: title,</span><br><span class="line">    <span class="comment">// ⋯⋯</span></span><br><span class="line">    <span class="comment">// ,</span></span><br><span class="line">    <span class="comment">// author: store.findRecord(&#x27;user&#x27;, 1)   //设置关联</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 第二种设置关联关系方法，在外部手动调用set方法设置</span></span><br><span class="line">article.set(<span class="string">&#x27;author&#x27;</span>, store.findRecord(<span class="string">&#x27;user&#x27;</span>, <span class="number">1</span>));</span><br></pre></td></tr></table></figure>
<p>这种方式可以直接动态根据user的id属性值获取到记录，再设置关联关系。新增介绍完了，接着介绍记录的更新。</p>
<p>##2，更新记录</p>
<p>更新相对于新增来说非常相似。请看下面的代码段：<br>首先在模板上增加更新的设置代码，修改子模板<code>articles/article.hbs</code>：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  app/templates/articles/article.hbs  --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>&#123;&#123;model.title&#125;&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span> = <span class="string">&quot;body&quot;</span>&gt;</span></span><br><span class="line">&#123;&#123;model.body&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">hr</span>&gt;</span></span><br><span class="line">更新测试<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">title: &#123;&#123;input value=model.title&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">body：<span class="tag">&lt;<span class="name">br</span>&gt;</span> &#123;&#123;textarea value=model.body cols=&quot;80&quot; rows=&quot;3&quot;&#125;&#125;<span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> &#123;&#123;<span class="attr">action</span> &#x27;<span class="attr">updateArticleById</span>&#x27; <span class="attr">model.id</span>&#125;&#125;&gt;</span>更新文章信息<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>增加一个<code>controller</code>，用户处理子模板提交的修改信息。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ember g controller articles&#x2F;article</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  app/controllers/articles/article.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    actions: &#123;</span><br><span class="line">        <span class="comment">// 根据文章id更新</span></span><br><span class="line">        updateArticleById: <span class="function"><span class="keyword">function</span>(<span class="params">params</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> title = <span class="built_in">this</span>.get(<span class="string">&#x27;model.title&#x27;</span>);</span><br><span class="line">            <span class="keyword">var</span> body = <span class="built_in">this</span>.get(<span class="string">&#x27;model.body&#x27;</span>);</span><br><span class="line">            <span class="built_in">this</span>.store.findRecord(<span class="string">&#x27;article&#x27;</span>, params).then(<span class="function"><span class="keyword">function</span>(<span class="params">art</span>) </span>&#123;</span><br><span class="line">                art.set(<span class="string">&#x27;title&#x27;</span>, title);</span><br><span class="line">                art.set(<span class="string">&#x27;body&#x27;</span>, body);</span><br><span class="line"></span><br><span class="line">                <span class="comment">//  保存更新的值到Store</span></span><br><span class="line">                art.save();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>在左侧选择需要更新的数据，然后在右侧输入框中修改需要更新的数据，在修改过程中可以看到被修改的信息会立即反应到界面上，这个是因为Ember自动更新Store中的数据（还记得很久前讲过的观察者（observer）吗？）。</p>
<p><img src="http://static.oschina.net/uploads/img/201510/21020549_Xggt.png" alt="结果截图"></p>
<p>如果你没有点击“更新文章信息”提交，你修改的信息不会更新到firebase。页面刷新后还是原来样子，如果你点击了“更新文章信息”数据将会把更新的信息提交到firebase。</p>
<p>由于<code>save</code>、<code>findRecord</code>方法返回值是一个<code>promises</code>对象，所以你还可以针对出错情况进行处理。比如下面的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> user = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;user&#x27;</span>, &#123;</span><br><span class="line">    <span class="comment">//  ⋯⋯</span></span><br><span class="line">&#125;);</span><br><span class="line">user.save().then(<span class="function"><span class="keyword">function</span>(<span class="params">fulfill</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  保存成功</span></span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  保存失败</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">this</span>.store.findRecord(<span class="string">&#x27;article&#x27;</span>, params).then(<span class="function"><span class="keyword">function</span>(<span class="params">art</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  ⋯⋯</span></span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//  出错处理代码</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>具体代码我就不演示了，请读者自己编写测试吧！！</p>
<p>##3，删除记录</p>
<p>既然有了新增那么通常就会有删除。记录的删除与修改非常类似，也是首先查询出要删除的数据，然后执行删除。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   app/controllers/articles.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line"></span><br><span class="line">    actions: &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//  表单提交，保存数据到Store。Store会自动更新到firebase</span></span><br><span class="line">        saveItem: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="comment">// 省略</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="comment">//  根据id属性值删除数据</span></span><br><span class="line">        delById : <span class="function"><span class="keyword">function</span>(<span class="params">params</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//  任意获取一个作为判断表单输入值</span></span><br><span class="line">            <span class="keyword">if</span> (params &amp;&amp; confirm(<span class="string">&quot;你确定要删除这条数据吗？?&quot;</span>)) &#123;</span><br><span class="line">                <span class="comment">//  执行删除</span></span><br><span class="line">                <span class="built_in">this</span>.store.findRecord(<span class="string">&#x27;article&#x27;</span>, params).then(<span class="function"><span class="keyword">function</span>(<span class="params">art</span>) </span>&#123;</span><br><span class="line">                    art.destroyRecord();</span><br><span class="line">                    alert(<span class="string">&#x27;删除成功！&#x27;</span>);</span><br><span class="line">                &#125;, <span class="function"><span class="keyword">function</span>(<span class="params">error</span>) </span>&#123;</span><br><span class="line">                    alert(<span class="string">&#x27;删除失败！&#x27;</span>);</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>修改显示数据的模板，增加删除按钮，并传递数据的<code>id</code>值到<code>controller</code>。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--  app/templates/articles.hbs  --&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;container&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;row&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4 col-xs-4&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;list-group&quot;</span>&gt;</span></span><br><span class="line">            &#123;&#123;#each model as |item|&#125;&#125;</span><br><span class="line">                <span class="tag">&lt;<span class="name">li</span> <span class="attr">class</span>=<span class="string">&quot;list-group-item&quot;</span>&gt;</span></span><br><span class="line">                    <span class="comment">&lt;!--设置路由，路由的层级与router.js里定义的要一致 --&gt;</span></span><br><span class="line">                     &#123;&#123;#link-to &#x27;articles.article&#x27; item.id&#125;&#125;</span><br><span class="line">                        &#123;&#123;item.title&#125;&#125; -- <span class="tag">&lt;<span class="name">small</span>&gt;</span>&#123;&#123;item.category&#125;&#125;<span class="tag">&lt;/<span class="name">small</span>&gt;</span> -- <span class="tag">&lt;<span class="name">small</span>&gt;</span>&#123;&#123;item.author.username&#125;&#125;<span class="tag">&lt;/<span class="name">small</span>&gt;</span></span><br><span class="line">                    &#123;&#123;/link-to&#125;&#125;</span><br><span class="line">                    <span class="tag">&lt;<span class="name">button</span> &#123;&#123;<span class="attr">action</span> &#x27;<span class="attr">delById</span>&#x27; <span class="attr">item.id</span>&#125;&#125;&gt;</span>删除<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">            &#123;&#123;/each&#125;&#125;</span><br><span class="line">            <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">        // ⋯⋯省略其他代码</span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><img src="http://static.oschina.net/uploads/img/201510/21020550_LCXS.png" alt="截图"></p>
<p>结果如上图，点击第二条数据删除按钮。弹出提示窗口，点击“确定”之后成功删除数据，并弹出“删除成功！”，到firebase后台查看数据，确实已经删除成功。<br>然而与此关联的user却没有删除，正常情况下也应该是不删除关联的user数据的。<br>最终结果只剩下一条数据：</p>
<p><img src="http://static.oschina.net/uploads/img/201510/21020550_zI51.png" alt="截图"></p>
<p>到此，有关新增、更新、删除的方法介绍完毕。已经给出了详细的演示实例，我相信，如果你也亲自在自己的项目中实践过，那么掌握这几个方法是很容易的！<br><br><br>博文完整代码放在<a target="_blank" rel="noopener" href="https://github.com/ubuntuvim/my_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能有出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/models/%E6%9F%A5%E8%AF%A2%E8%AE%B0%E5%BD%95/" rel="next" title="查询记录">
          查询记录
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/models/%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9E%8B/" rel="prev" title="定义模型">
            定义模型
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1%EF%BC%8C%E6%96%B0%E5%BB%BA%E8%AE%B0%E5%BD%95"><span class="toc-text">1，新建记录</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '新建、更新、删除记录', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
